package com.example.shuiyin.service.parser;

import com.example.shuiyin.exception.AppException;
import com.example.shuiyin.exception.ErrorCode;
import com.example.shuiyin.utils.HttpUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@RequiredArgsConstructor
@Slf4j
public class WeiboParser implements PlatformParser {

    private final HttpUtils httpUtils;
    
    @Override
    public String parse(String url) {
        log.info("解析微博链接: {}", url);
        
        try {
            // 获取HTML内容
            String htmlContent = httpUtils.getHtml(url);
            
            // 正则匹配视频地址
            Pattern pattern = Pattern.compile("video_src=([^&\"]+)");
            Matcher matcher = pattern.matcher(htmlContent);
            
            if (matcher.find()) {
                String videoUrl = matcher.group(1);
                // URL解码
                videoUrl = java.net.URLDecoder.decode(videoUrl, "UTF-8");
                
                log.info("微博视频解析成功: {}", videoUrl);
                return videoUrl;
            }
            
            throw new AppException("解析微博视频地址失败", ErrorCode.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            log.error("解析微博链接异常", e);
            throw new AppException("解析微博链接异常: " + e.getMessage(), ErrorCode.INTERNAL_SERVER_ERROR);
        }
    }
} 